package com.atzly.community.controller;

import com.atzly.community.constant.CommentConstant;
import com.atzly.community.entity.Event;
import com.atzly.community.entity.User;
import com.atzly.community.event.EventProducter;
import com.atzly.community.service.LikeService;
import com.atzly.community.utils.CommunityUtils;
import com.atzly.community.utils.HostHolder;
import com.atzly.community.utils.RedisKeyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 点赞业务
 * 补充:系统通知功能
 *
 * @author zlysimida
 * @date 2021/8/30 - 16:42
 */
@Controller
@RequestMapping("/like")
public class LikeController implements CommentConstant {

    @Autowired
    private LikeService likeService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private EventProducter producter;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/praise")
    @ResponseBody
    public String praise(int entityId, int entityType, int entityUserId, int postId) {
        User user = hostHolder.getUserFromThread();
        // 点赞
        likeService.like(user.getId(), entityType, entityId, entityUserId);
        // 数量
        long likeCount = likeService.findEntityLikeCount(entityType, entityId);
        // 状态
        int likeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);
        // 返回的结果
        Map<String, Object> map = new HashMap<>();
        map.put("likeCount", likeCount);
        map.put("likeStatus", likeStatus);
        // 触发点赞事件,发送通知
        if (likeStatus == 1) {
            Event event = new Event()
                    .setTopic(TOPIC_LIKE_KEY)
                    .setUserId(user.getId())
                    .setEntityType(entityType)
                    .setEntityId(entityId)
                    .setEntityUserId(entityUserId)
                    .setData("postId", postId);
            producter.sendMessage(event);
        }
        // 对帖子点赞进行记录
        if (entityType == ENTITY_TYPE_POST) {
            // 点赞需要记录下该帖子
            String redisKey = RedisKeyUtils.getPostScoreKey();
            redisTemplate.opsForSet().add(redisKey, postId);
        }
        return CommunityUtils.JsontoString(0, null, map);
    }
}
